package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.MerchantNotifyDetails;
import cn.com.connext.scrm.service.WxMerchantRollService;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.utils.DateUtils;
import cn.com.connext.scrm.utils.wechat.WeiXinUtils;
import cn.com.connext.scrm.web.rest.req.WxBusinessVolumeReq;
import cn.com.connext.scrm.web.rest.req.WxMerchanRollQueryPage;
import cn.com.connext.scrm.web.rest.vm.MerchantRollVM;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author: ZHaoYul
 * @date: 2021/9/13 14:34
 */

@RestController
@RequestMapping("/api/wxMerchantRoll/")
public class WxMerchantRollResource {
    private final Logger logger = LoggerFactory.getLogger(WxMerchantRollResource.class);
    @Autowired
    private WxMerchantRollService wxMerchantRollService;

    @Autowired
    private WeiXinUtils weiXinUtils;

    /**
     * 新增编辑
     * @param jsonObject
     * @return
     */
    @PostMapping("saveOrUpWxMerchantRoll")
    @ResponseBody
    public JsonResult saveWxMerchantRoll(@RequestBody JSONObject jsonObject){
        JsonResult jsonResult = new JsonResult();
        //新增编辑数据
        try {
            wxMerchantRollService.saveOrUpdate(jsonObject);
        } catch (Exception e) {
            logger.info("异常信息 e:{} ",e);
            jsonResult.setMessage("操作异常");
            jsonResult.setState(JsonResult.ERROR);
        }

        return jsonResult;
    }

    @PostMapping("wxCallBusinessVolume")
    @ResponseBody
    public void callWxHxMessage(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject jsonObject) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        logger.info("微信回调参数 jsonObject:{}",jsonObject);
        Map<String,Object> map = new HashMap<>();
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
             bufferedReader = request.getReader();
             String str;
             while ((str = bufferedReader.readLine())!=null){
                 stringBuilder.append(str);
             }
            bufferedReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("request 解析body 数据为：{}", JSON.toJSONString(stringBuilder.toString()));
        if (weiXinUtils.responseSignVerify(request.getHeader("Wechatpay-Serial"), request.getHeader("Wechatpay-Signature")
            , request.getHeader("Wechatpay-Timestamp"), request.getHeader("Wechatpay-Nonce"), jsonObject.toJSONString())) {

            try {
                JSONObject resource = jsonObject.getJSONObject("resource");
                String s = weiXinUtils.decryptResponseBody(resource.getString("associated_data"),
                    resource.getString("nonce"), resource.getString("ciphertext"));
                logger.info("解密resource={}",s);

                JSONObject jsonObject1 = JSONObject.parseObject(s);
                //2019-12-17T10:35:53+08:00
                if (StringUtils.isNotBlank(jsonObject1.getString("send_time"))) {
                    logger.info("wx返回领卷时间 send_time :{}",jsonObject1.getString("send_time"));

                    jsonObject1.put("send_time",DateUtils.toDateFormattingYYYYMMDDTSS(jsonObject1.getString("send_time")));
                    logger.info("时间转换后 jsonObject: {} ",jsonObject1);
                }
                MerchantNotifyDetails merchantNotifyDetails1 = JSONObject.parseObject(s, MerchantNotifyDetails.class);
                JSONObject attach_info = jsonObject1.getJSONObject("attach_info");
                if (null != attach_info) {
                    merchantNotifyDetails1.setTransaction_id(attach_info.getString("transaction_id"));
                    merchantNotifyDetails1.setAct_code( attach_info.getString("act_code"));
                }
                MerchantNotifyDetails merchantNotifyDetails = wxMerchantRollService.getNotifyObjByCode(merchantNotifyDetails1.getCode());
                logger.info("根据code 查询出信息为：{} ",JSON.toJSONString(merchantNotifyDetails));
                merchantNotifyDetails = wxMerchantRollService.updateNotifyById(merchantNotifyDetails1);
                response.setStatus(200);
                map.put("code","SUCCESS");
                map.put("message","SUCCESS");
                logger.info("callWxHxMessage 更新成功");
            } catch (Exception e) {
                logger.info(e.getMessage());
                response.setStatus(500);
                map.put("code","ERROR");
                map.put("message","数据处理异常");
            }

        } else {
            logger.info("签名验证不通过");
            response.setStatus(500);
            map.put("code","ERROR");
            map.put("message","签名验证失败");
        }

        try {
            response.setHeader("Content-type", ContentType.JSON.toString());
            response.getOutputStream().write(JSONUtil.toJsonStr(map).getBytes(StandardCharsets.UTF_8));
            response.flushBuffer();
        } catch (IOException e) {
            logger.info("返回wx数据response 出现异常");
        }

    }

//    public static void main(String[] args) {
//        //查询商家卷通知地址
//        String url = "https://api.mch.weixin.qq.com/v3/marketing/busifavor/callbacks?mchid=1612505750";
//            //序列号
//        String merchantSerialNumber = "32075FA334FA59896AEF7879670E82AB13075120";
//            //商户号
//        String merchantId = "1612505750";
//        String apiV3Key = "20210805A161000ADiageoOmata0417y";
//            //私钥
//            PrivateKey merchantPrivateKey = null;
//            WechatPayHttpClientBuilder builder = null;
//            String bodyAsString = null;
//            try {
//                merchantPrivateKey = PemUtil.loadPrivateKey(
//                    new FileInputStream("D://apiclient_key.pem"));
//                //不需要传入微信支付证书了 需要v3Key
//                AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
//                    new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
//                    apiV3Key.getBytes("utf-8"));
//                builder = WechatPayHttpClientBuilder.create()
//                    .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
//                    .withValidator(new WechatPay2Validator(verifier));
//                HttpClient httpClient = builder.build();
//                HttpGet httpPost = new HttpGet(url);
//                httpPost.addHeader("Accept", "application/json");
//                httpPost.addHeader("Content-type","application/json; charset=utf-8");
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
////            ObjectMapper objectMapper = new ObjectMapper();
////            ObjectNode rootNode = objectMapper.createObjectNode();
////            HttpGet.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
//                CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
//                try {
////                    objectMapper.writeValue(bos, rootNode);
//                    bodyAsString = EntityUtils.toString(response.getEntity());
//                    System.out.println(bodyAsString);
//                    System.out.println(bodyAsString);
//                    System.out.println(bodyAsString);
//                    System.out.println(bodyAsString);
////                    return bodyAsString;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            } catch (FileNotFoundException | UnsupportedEncodingException e) {
//                e.printStackTrace();
//            } catch (ClientProtocolException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//    }

//    public static void main(String[] args) {
//        //设置商家卷通知地址
//        String url = "https://api.mch.weixin.qq.com/v3/marketing/busifavor/callbacks";
//
//        //序列号
//        String merchantSerialNumber = "32075FA334FA59896AEF7879670E82AB13075120";
//        //商户号
//        String merchantId = "1612505750";
//        String apiV3Key = "20210805A161000ADiageoOmata0417y";
//        //私钥
//        PrivateKey merchantPrivateKey = null;
//        WechatPayHttpClientBuilder builder = null;
//        String bodyAsString = null;
//        try {
//            merchantPrivateKey = PemUtil.loadPrivateKey(
//                new FileInputStream("D://apiclient_key.pem"));
//            //不需要传入微信支付证书了 需要v3Key
//            AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
//                new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
//                apiV3Key.getBytes("utf-8"));
//            builder = WechatPayHttpClientBuilder.create()
//                .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
//                .withValidator(new WechatPay2Validator(verifier));
//            HttpClient httpClient = builder.build();
//            HttpPost httpPost = new HttpPost(url);
//            httpPost.addHeader("Accept", "application/json");
//            httpPost.addHeader("Content-type","application/json; charset=utf-8");
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            ObjectMapper objectMapper = new ObjectMapper();
//            ObjectNode rootNode = objectMapper.createObjectNode();
//            rootNode.put("mchid",merchantId);
//            rootNode.put("notify_url","https://wxadmin.singlemalts.com.cn/gateway/note-service/api/wxMerchantRoll/wxCallBusinessVolume");
//            objectMapper.writeValue(bos, rootNode);
//            httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
//            CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
//            bodyAsString = EntityUtils.toString(response.getEntity());
//            System.out.println(bodyAsString);
//            System.out.println(bodyAsString);
//            System.out.println(bodyAsString);
//            System.out.println(bodyAsString);
//
//        } catch (FileNotFoundException | UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 获取用户商家卷详情
     * @return
     */
    @PostMapping("getUserMerchantRollDetails")
    @ResponseBody
    public JsonResult getUserMerchantRollDetails(@RequestBody MerchantRollVM vm){
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isBlank(vm.getCoupon_code())||StringUtils.isBlank(vm.getAppid())
            ||StringUtils.isBlank(vm.getOpenid())) {
            jsonResult.setState(-1);
            jsonResult.setMessage("参数不正确");
            return jsonResult;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();
//        objectNode.put("","");
        StringBuffer stringBuffer = new StringBuffer();
        String url = stringBuffer.append("https://api.mch.weixin.qq.com/v3/marketing/busifavor/users/")
            .append(vm.getOpenid())
            .append("/coupons/")
            .append(vm.getCoupon_code())
            .append("/appids/")
            .append(vm.getAppid()).toString();
        String wxHttpClient = weiXinUtils.getWxHttpClient(url, objectMapper, objectNode);
        if (StringUtils.isNotBlank(wxHttpClient)) {
            JSONObject jsonObject = JSONObject.parseObject(wxHttpClient);
            if (StringUtils.isBlank(jsonObject.getString("belong_merchant"))) {
                jsonResult.setState(JsonResult.ERROR);
                jsonResult.setMessage("查询失败");
            } else {
                jsonResult.setState(JsonResult.SUCCESS);
                jsonResult.setData(jsonObject);
            }

            //暂时停用 等待需求制定
//            wxMerchantRollService.packMerchantData(jsonObject);
        } else {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("查询失败");
        }
        return jsonResult;
    }

    /**
     * 查询商家卷详情
     * @param vm
     * @return
     */
    @PostMapping("getMerchantRoll")
    @ResponseBody
    public JsonResult getMerchantRoll(@RequestBody MerchantRollVM vm){
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isBlank(vm.getStock_id())) {
            jsonResult.setMessage("参数缺失");
            jsonResult.setState(JsonResult.ERROR);
            return jsonResult;
        }

        StringBuilder str = new StringBuilder();
        str.append("https://api.mch.weixin.qq.com/v3/marketing/busifavor/stocks/").append(vm.getStock_id());
        String url = str.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();
        String wxHttpClient = weiXinUtils.getWxHttpClient(url, objectMapper, objectNode);
        if (StringUtils.isNotBlank(wxHttpClient)) {
            JSONObject jsonObject = JSONObject.parseObject(wxHttpClient);
            if (StringUtils.isBlank(jsonObject.getString("stock_name"))) {
                jsonResult.setState(JsonResult.ERROR);
                jsonResult.setMessage("查询失败");
            } else {
                jsonResult.setState(JsonResult.SUCCESS);
                jsonResult.setData(jsonObject);
            }
        } else {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("查询失败");
        }


        return jsonResult;

    }

    /**
     * 分页查询用户卷 商家卷
     * @param vm
     * @return
     */
    @PostMapping("getUserMerchantRoll")
    @GetMapping
    public JsonResult getUserMerchantRoll(@RequestBody MerchantRollVM vm){
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isBlank(vm.getOpenid())||StringUtils.isBlank(vm.getAppid())) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("参数缺失");
            return jsonResult;
        }
        StringBuffer str = new StringBuffer();
        str.append("https://api.mch.weixin.qq.com/v3/marketing/busifavor/users/")
            .append(vm.getOpenid())
            .append("/coupons")
            .append("?appid="+vm.getAppid());
        //批次号
        if (StringUtils.isNotBlank(vm.getStock_id())) {
            str.append("&stock_id="+vm.getStock_id());
        }
        //卷状态
        if (StringUtils.isNotBlank(vm.getCoupon_state())) {
            str.append("&coupon_state="+vm.getCoupon_state());
        }
        //创建批次的商户号
        if (StringUtils.isNotBlank(vm.getCreator_merchant())) {
            str.append("&creator_merchant="+vm.getCreator_merchant());
        }
        //批次归属商户号
        if (StringUtils.isNotBlank(vm.getBelong_merchant())) {
            str.append("&belong_merchant="+vm.getBelong_merchant());
        }
        //批次发放商户号
        if (StringUtils.isNotBlank(vm.getSender_merchant())) {
            str.append("&sender_merchant="+vm.getSender_merchant());
        }
        //分页
        if (vm.getOffset()>0) {
            str.append("&offset="+vm.getOffset());
        }
        //分页
        if (vm.getLimit()>0) {
            str.append("&limit="+vm.getLimit());
        }

        String url = str.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();
        String wxHttpClient = weiXinUtils.getWxHttpClient(url, objectMapper, objectNode);

        if (StringUtils.isNotBlank(wxHttpClient)) {
            JSONObject jsonObject = JSONObject.parseObject(wxHttpClient);
            if (null == jsonObject.getInteger("total_count")) {
                jsonResult.setState(JsonResult.ERROR);
                jsonResult.setMessage("查询失败");
            } else {
                jsonResult.setState(JsonResult.SUCCESS);
                jsonResult.setData(jsonObject);
            }
        } else {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("查询失败");
        }
        return jsonResult;
    }

    /**
     * 核销用户卷
     * @param vm
     * @return
     */
    @PostMapping("hxUserMerchantRoll")
    @ResponseBody
    public JsonResult hxUserMerchantRoll(@RequestBody MerchantRollVM vm){
        JsonResult jsonResult = new JsonResult();

        if (StringUtils.isBlank(vm.getCoupon_code())
            ||StringUtils.isBlank(vm.getAppid())
            ||StringUtils.isBlank(vm.getUse_request_no())) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("参数缺失");
            return jsonResult;
        }
        StringBuffer str = new StringBuffer();
        str.append("https://api.mch.weixin.qq.com/v3/marketing/busifavor/coupons/use");
        String url = str.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("coupon_code",vm.getCoupon_code());
        objectNode.put("appid",vm.getAppid());
        objectNode.put("use_time",new SimpleDateFormat("yyyy-MM-dd'T'HH：mm：ssXXX").format(new Date()));
        objectNode.put("use_request_no",vm.getUse_request_no());
        if (StringUtils.isNotBlank(vm.getStock_id())) {
            objectNode.put("stock_id",vm.getStock_id());
        }
        if (StringUtils.isNotBlank(vm.getOpenid())) {
            objectNode.put("openid",vm.getOpenid());
        }
        String wxHttpClient = weiXinUtils.postWxHttpClient(url, objectMapper, objectNode);

        if (StringUtils.isNotBlank(wxHttpClient)) {
            JSONObject jsonObject = JSONObject.parseObject(wxHttpClient);
            if (null == jsonObject.getInteger("stock_id")) {
                jsonResult.setState(JsonResult.ERROR);
                jsonResult.setMessage("核销失败");
            } else {
                jsonResult.setState(JsonResult.SUCCESS);
                jsonResult.setData(jsonObject);
            }
        } else {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("核销失败");
        }

        return jsonResult;

    }


    /**
     * 启用
     * @param req
     * @return
     */
    @PostMapping("startWxBusinessVolume")
    @ResponseBody
    public JsonResult startWxBusinessVolume(@RequestBody WxBusinessVolumeReq req){
        JsonResult jsonResult = new JsonResult();
        logger.info("启用商家卷入参 jsonObject:{}",JSON.toJSONString(req));
        if (StringUtils.isBlank(req.getMainId())) {
            jsonResult.setState(JsonResult.ERROR);
            jsonResult.setMessage("id 不能为空");
        }
        jsonResult = wxMerchantRollService.startWxBusinessVolume(req);
        return jsonResult;
    }
    /**
     * 列表
     * @param req
     * @return
     */
    @PostMapping("getPageList")
    @ResponseBody
    public JsonResult getPageList(@RequestBody WxMerchanRollQueryPage req){
        logger.info("查询商家卷列表 req:{}",JSON.toJSONString(req));
        return wxMerchantRollService.page(req);
    }
    /**
     * 详情
     * @param req
     * @return
     */
    @PostMapping("getDetails")
    @ResponseBody
    public JsonResult getDetails(@RequestBody WxBusinessVolumeReq req){
        logger.info("查询商家卷详情 req:{}",JSON.toJSONString(req));
        return wxMerchantRollService.details(req);
    }

    /**
     * 删除
     * @param req
     * @return
     */
    @PostMapping("deleteOne")
    @ResponseBody
    public JsonResult deleteOne(@RequestBody WxBusinessVolumeReq req){
        logger.info("删除商家卷数据 req:{}",JSON.toJSONString(req));
        return wxMerchantRollService.deleteOne(req);
    }
    /**
     * 删除
     * @param req
     * @return
     */
    @PostMapping("getNeckRollList")
    @ResponseBody
    public JsonResult getNeckRollList(@RequestBody WxMerchanRollQueryPage req){
        logger.info("领劵事件列表 req:{}",JSON.toJSONString(req));
        return wxMerchantRollService.getNeckRollList(req);
    }

}
